28. 文件上传和下载

页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3> 文件上传 </h3>
<from action="FileUploadDemo" method="post" enctype="multipart/from-data">
选择文件:<input type="file", name="fileupload"/>
提交上传 <input type="submit", value="上传文件"/>
</from>
</body>
</html>

上传文件

commons-fileupload 包依赖 common-io, 所以需要先导入这两个包。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.itguigu.file;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUploadDemo extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取上传到的文件夹的路径
String uploadPath = this.getServletContext().getRealPath("/upload");

// 1. 导包
// 2. 创建工厂类
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 3. 创建 ServletFileUpload 对象
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 4. 解析参数 (parseRequest 返回一个List,里面是所有的参数,类型是 FileItem)
try {
List<FileItem> parseRequest = servletFileUpload.parseRequest(request);
// 5. 迭代获取的所有参数,判断是否是文件
for (FileItem fileItem : parseRequest) {
if (fileItem.isFormField() == false) {
// 6. 是文件,将其保存到 WebContent 下的 upload 文件夹下
File file = new File(uploadPath +"/"+ fileItem.getName());
fileItem.write(file);
}
}
} catch (Exception e) {
e.printStackTrace();
}
response.getWriter().write("success!");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

文件名相同

相同名称文件会被覆盖,使用 uuid 将文件变成唯一文件即可。

1
2
String uuid = UUID.randomUUID().toString().replace("-", "");
File file = new File(uploadPath +"/"+ uuid + fileItem.getName());

限制文件大小

1
2
3
4
// 设置单文件大小,单位是 B
servletFileUpload.setFileSizeMax(2*1024);
// 设置总文件的大小,单位是 B
// servletFileUpload.setSizeMax(sizeMax);

文件上传完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.itguigu.file;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUploadDemo extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
// 获取上传到的文件夹的路径
String uploadPath = this.getServletContext().getRealPath("/upload");

// 1. 导包
// 2. 创建工厂类
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 3. 创建 ServletFileUpload 对象
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 设置单文件大小,单位是 B
servletFileUpload.setFileSizeMax(2*1024);
// 设置总文件的大小,单位是 B
// servletFileUpload.setSizeMax(sizeMax);
// 4. 解析参数 (parseRequest 返回一个List,里面是所有的参数,类型是 FileItem)
try {
List<FileItem> parseRequest = servletFileUpload.parseRequest(request);
// 5. 迭代获取的所有参数,判断是否是文件
for (FileItem fileItem : parseRequest) {
if (fileItem.isFormField() == false) {
// 6. 是文件,将其保存到 WebContent 下的 upload 文件夹下
String uuid = UUID.randomUUID().toString().replace("-", "");
File file = new File(uploadPath +"/"+ uuid + fileItem.getName());
fileItem.write(file);
}
}
response.getWriter().write("文件上传失败!");
} catch (FileSizeLimitExceededException e) {
e.printStackTrace();
response.getWriter().write("单文件大小不能超过 2k!");
} catch (Exception e) {
e.printStackTrace();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.itguigu.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;


public class FileDownloadDemo extends HttpServlet {
private static final long serialVersionUID = 1L;

@SuppressWarnings("resource")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");

// 获取文件名
String filename = request.getParameter("filename");
// 获取文件的真实路径
String realPath = this.getServletContext().getRealPath("/WEB-INF/download");
String downloadPath = realPath + "/" +filename;

//设置浏览器响应体文件类型
String mimeType = request.getServletContext().getMimeType(filename);
response.setContentType(mimeType);
//解决文件名中文乱码问题
String header = request.getHeader("User-Agent");
if(header != null && header.contains("Firefox")) {
filename = "=?utf-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?=";
}else {
filename = URLEncoder.encode(filename, "UTF-8");
}
//设置浏览器响应体内容格式,为附件格式。(告诉浏览器别播放,下载)
response.setHeader("Content-Disposition", "attachment; filename="+filename);

// 读取资源,同时写到客户端
FileInputStream fileInputStream = new FileInputStream(downloadPath);
// 创建写出流
ServletOutputStream outputStream = response.getOutputStream();
byte[] b = new byte[1024];
while (fileInputStream.read(b) != -1) {
outputStream.write(b);
}
outputStream.close();
fileInputStream.close();
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}